package com.itheima.server;

import com.itheima.pojo.Student;

import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;

/*
    此类功能：

    1.接收"服务器端线程"的增、删、改、查的业务请求；
    2.访问文件
    3.为线程返回查询结果

    此类设计说明：
    1.全部是公有、静态、同步方法。

 */
public class StudentDAO {
    //不需要创建对象
    private StudentDAO(){
    }

    //添加
    public static synchronized boolean addStudent(Student student) {
        ArrayList<Student> stuList = readAll();
        if (stuList == null) {//说明读取文件出错
            return false;
        }

        //获取最大ID
        if(stuList.size() != 0) {//有数据
            student.setId(stuList.get(stuList.size() - 1).getId() + 1);//取最后一个对象的id + 1
        }else{
            student.setId(1);//第一次添加，文件中没有内容
        }
        stuList.add(student);
        writeAll(stuList);
        return true;
    }

    //修改
    public static synchronized boolean updateStudent(Student student) {
        ArrayList<Student> stuList = readAll();
        if (stuList == null) {//说明读取文件出错
            return false;
        }
        System.out.println("修改的数据：" + student);
        for (int i = 0;i < stuList.size() ; i++) {
            Student stu = stuList.get(i);
            if(stu.getId() == student.getId()){
                stuList.set(i, student);
                writeAll(stuList);//写回文件
                return true;
            }
        }
        return false;//没找到
    }

    //删除
    public static synchronized boolean deleteById(int  id) {
        ArrayList<Student> stuList = readAll();
        if (stuList == null) {//说明读取文件出错
            return false;
        }
        for (int i = 0; i < stuList.size(); i++) {
            Student stu = stuList.get(i);
            if (stu.getId() == id) {
                stuList.remove(i);
                writeAll(stuList);
                return true;
            }
        }
        return false;
    }
    //查询所有
    public static synchronized ArrayList<Student> findAll(){
        ArrayList<Student> stuList = readAll();
        if (stuList == null) {//说明读取文件出错
            return null;
        }
        return stuList;
    }

    //根据ID查询一条记录
    public static Student findById(int id) {
        ArrayList<Student> stuList = readAll();
        if (stuList == null) {//说明读取文件出错
            return null;
        }
        for (int i = 0; i < stuList.size(); i++) {
            Student stu = stuList.get(i);
            if (stu.getId() == id) {
                return stu;
            }
        }
        return null;//没找到
    }

    //读取所有数据
    private static ArrayList<Student> readAll()  {

        ArrayList<Student> stuList = new ArrayList<>();
        String row = null;
        String decode = null;
        try {
            decode = URLDecoder.decode(StudentDAO.class.getResource("/").toString(), "UTF-8");
            decode = decode.replace("file:/", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        System.out.println(decode);
        File file = new File(decode + "student.txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try(
                BufferedReader bufIn = new BufferedReader(
                        new FileReader(decode + "student.txt"));
                ) {
            while ((row = bufIn.readLine()) != null) {
                String[] rowArray = row.split(",");

                Student stu = new Student();
                stu.setId(Integer.parseInt(rowArray[0]));
                stu.setName(rowArray[1]);
                stu.setSex(rowArray[2]);
                stu.setAge(Integer.parseInt(rowArray[3]));

                stuList.add(stu);
            }
        } catch (IOException e) {
            return null;
        }
        return stuList;
    }
    //写入ArrayList<Student>
    private static void writeAll(ArrayList<Student> stuList){
        String decode = null;
        try {
            decode = URLDecoder.decode(StudentDAO.class.getResource("/").toString(), "UTF-8");
            decode = decode.replace("file:/", "");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try (FileWriter out = new FileWriter(decode + "student.txt")) {
            for (Student stu : stuList) {
                out.write(stu.getId() + "," + stu.getName() + "," + stu.getSex() + "," + stu.getAge());
                out.write("\r\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
